package com.web.Controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.web.common.JsonResult;
import com.web.model.UsersModel;

public class AdminmgController extends Controller{
	private static Logger logger = Logger.getLogger(AdminmgController.class);
	
	public void index() {
		renderText("管理首页");
		redirect("/adminmg/showUser");
	}
	public void loginout() {
		
		 Subject currentUser = SecurityUtils.getSubject();
		 logger.debug("登出="+currentUser.getPrincipal().toString());
		 try {
		        currentUser.logout();
		        
		    } catch (Exception e) {
		    	logger.debug("登出发生错误", e);
		    }
		redirect("/login/");
	}
	@RequiresPermissions("showUser")
	public void showUser(){
		String parastr = "";
		String para =getPara("id","");
		String paraurl ="";
		int pageIndex = this.getParaToInt("p", 1);
		if(para.isEmpty()){
			setAttr("para", "");
			parastr = " order by id desc";
		}else{
			pageIndex = 1;
			paraurl = "&id="+para;
			parastr = " where id="+para;
			
		}
		setAttr("paraurl", paraurl);
		
		Page<UsersModel> page = UsersModel.dao.paginate(pageIndex, 5, "select *  ",  " from users "+parastr);
		
		String pageurl = "";
		setAttr("pageurl", pageurl);
		setAttr("list", page.getList());
		setAttr("page", page);
		render("/adminmg/showuser.html");
	}
	@RequiresPermissions("lookUser")
	public void lookUser() {
		Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Record userinfo = (Record) session.getAttribute("userinfo");
        int idValue= getParaToInt(0,0 );
      
		
		UsersModel u =UsersModel.dao.findById(idValue);
		setAttr("list", u);
		List<Record> role_info = Db.find("select * from roles,user_roles where roles.id=user_roles.role_id and user_roles.user_id = ?",idValue);
		int on =0;
		for(Record tmp: role_info)  
        {  
           
            if(tmp.getInt("role_id") == 3){
            	 on =1;
            }
        }  
		setAttr("on", on);
		setAttr("role_info", role_info);
		
		logger.info(u.getStr("real_name"));
		render("/adminmg/lookUser.html");
	}
	@RequiresPermissions("showByid")
	public void showByid() {
		Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Record userinfo = (Record) session.getAttribute("userinfo");
        int idValue=0;
        if(currentUser.hasRole("admin")){
        	idValue=getParaToInt(0,0 );
        }else{
        	idValue=userinfo.getInt("id");
        }
		
		UsersModel u =UsersModel.dao.findById(idValue);
		setAttr("list", u);
		List<Record> role_info = Db.find("select * from roles,user_roles where roles.id=user_roles.role_id and user_roles.user_id = ?",idValue);
		int on =0;
		for(Record tmp: role_info)  
        {  
           
            if(tmp.getInt("role_id") == 3){
            	 on =1;
            }
        }  
		setAttr("on", on);
		setAttr("role_info", role_info);
		logger.info(u.getStr("real_name"));
		render("/adminmg/showByid.html");
	}
	@RequiresPermissions("saveByid")
	public void saveByid() {
		int idValue=getParaToInt("id",0);
		int on=getParaToInt("on",0);
		String top = getPara("top" , "").trim();
		String username = getPara("mobile" , "0").trim();
		
		String card = getPara("card" , "0");
		String real_name =getPara("real_name" ,"").trim();
		String short_name = getPara("short_name" , "0");
		int up =getParaToInt("up" ,1);
		String sex =getPara("sex" ,"");
		String high =getPara("high" ,"");
		String weight =getPara("weight" ,"");
		String education =getPara("education" ,"");
		String hometown =getPara("hometown" ,"");
		String work =getPara("work" ,"");
		String workaddr =getPara("workaddr" ,"");
		String myself =getPara("myself" ,"");
		String birthday =getPara("birthday" ,"");
		String others =getPara("others" ,"");
		String push =getPara("push" ,"0");
		String fang =getPara("fang" ,"");
		String che =getPara("che" ,"");
		String msg = "";
		card=card.toUpperCase();
		boolean i =UsersModel.dao.findById(idValue)		
				.set("username", username)
				.set("card", card)
				.set("real_name", real_name)
				.set("short_name", short_name)
				.set("sex", sex).set("birthday", birthday)
				.set("high", high).set("weight", weight)
				.set("education", education).set("hometown", hometown)
				.set("work", work).set("workaddr", workaddr)
				.set("myself", myself).set("others", others)
				.set("push", push).set("fang", fang).set("che", che).set("top", top)
				.set("up", up).update();
		logger.info(i);
		if(i){
			msg="更新成功";
			Subject currentUser = SecurityUtils.getSubject();
			if(currentUser.hasRole("admin") &&  on==1)
			{
				
				Db.update(" UPDATE user_roles SET role_id=3 WHERE user_id=?",idValue);

			}
		}else{
			msg="更新失败";
		}
		
		setAttr("redirMsg", msg);
		setAttr("redirUrl", "/adminmg/showUser");
		render("../_redirPage.html");
	}	
	public void password(){
		
	}
	public void dopassword(){
		PropKit.use("jfinal.properties");
		String pass=getPara("pass");
		String password=getPara("password","");
		if(password.length()<6){
			renderJson(new JsonResult(JsonResult.ERROR, "密码长度须6位以上"));
			return;
		}
		String salt=PropKit.get("salt");
		pass= new Md5Hash(pass, salt).toString();
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		Record userinfo = (Record) session.getAttribute("userinfo");
		logger.info(pass);
		logger.info(userinfo.get("password"));
		if(pass.equals(userinfo.get("password"))){
			password= new Md5Hash(password, salt).toString();
			Record user = Db.findById("users", userinfo.getInt("id")).set("password", password);
			Db.update("users", user);
			renderJson(new JsonResult(JsonResult.SUCCESS, "修改成功"));
			return;
		}else{
			renderJson(new JsonResult(JsonResult.ERROR, "原密码不正确"));
			return;
		}
	}
}
